package dao.impl;

import dao.StudentDao;
import entity.Student;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import utils.DbUtil;

import java.util.List;

/**
 * Created by honghao on 2017/2/14.
 */
public class StudentDaoImpl implements StudentDao {
    private static SessionFactory sf = DbUtil.getSf();

    @Override
    public Student get(int id) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        Student st = (Student) session.get(Student.class, id);
        tx.commit();
        return st;
    }

    @Override
    public void save(Student student) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        session.save(student);
        tx.commit();
    }

    @Override
    public void delete(Student student) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        session.delete(student);
        tx.commit();
    }

    @Override
    public void delete(int id) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        Student student = (Student) session.get(Student.class, id);
        session.delete(student);
        tx.commit();
    }

    @Override
    public void update(Student student) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        session.update(student);
        tx.commit();
    }

    @Override
    public List<Student> findStudentByNameAndStuNumber(String name, String stuNumber)
    {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        Query query = session.createQuery("from Student where name=? and stuNumber=?");
        query.setParameter(0, name);
        query.setParameter(1, stuNumber);

        return query.list();
    }

    @Override
    public List<Student> findAllByPage(int pageNo, int pageSize) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        Query query = session.createQuery("from Student ");
        query.setFirstResult(pageNo);
        query.setMaxResults(pageSize);
        tx.commit();
        return query.list();
    }

    @Override
    public long getStudentCount() {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        Query query = session.createQuery("select count(*) from Student ");
        return ((Number) query.uniqueResult()).longValue();
    }
}
